package com.ch.forum.controller;

import com.ch.forum.bo.ResponseResult;
import com.ch.forum.utils.FileUtils;
import com.ch.forum.utils.RandomUtils;
import com.ch.forum.utils.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

@RequestMapping("/file")
@Controller
public class FileController {

    @Value("${upload.dir}")
    private String fileDir;

    @PostMapping("/upload-img")
    @ResponseBody
    public ResponseResult uploadImg(@RequestParam("file")MultipartFile file){
        if(file.isEmpty() || StringUtils.isBlank(file.getOriginalFilename())){
            return new ResponseResult(false,"文件或文件名不能为空");
        }
        String fileName = RandomUtils.getUUID();
        try {
            FileUtils.uploadFile(file.getBytes(), fileDir, fileName + ".jpg");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseResult(true,"上传成功", fileName);
    }


    @GetMapping("/read-img/{fileName}")
    @ResponseBody
    public void readImg(@PathVariable("fileName")String fileName,
                        HttpServletResponse response) throws Exception {
        FileUtils.readFileAndOutput(fileDir + fileName + ".jpg", response);
    }
}
